package yang.learn.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import yang.learn.entity.User;
import yang.learn.service.UserService;
import yang.learn.service.impl.UserServiceImpl;

import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("admin")
public class AdminController {

    @ResponseBody
    @RequestMapping("login")
    public ModelAndView login(User user, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:admin");
        if("admin".equals(user.getUser_account()) && "admin".equals(user.getUser_password())) {
            //生成一个token
            String token = UUID.randomUUID().toString();
            System.out.println("用户登录成功，获得token:" + token);
            HttpSession session = request.getSession();
            //服务端备份token
            session.setAttribute("token", token);
            //服务端备份用户信息
            //客户端存储token
            Cookie cookie = new Cookie("admin_uuid", token);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return modelAndView;
    }
    @ResponseBody
    @RequestMapping("queryAll")
    public ModelAndView queryAll(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:admin");
            if ("admin_success".equals(request.getAttribute("login_result"))){
                UserService userService = new UserServiceImpl();
                List<User> queryAll = userService.queryAll();
                modelAndView.addObject("user_list",queryAll);
            }
        return modelAndView;
    }
}
